#include "student.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

// 创建学生链表
StudentList* create_student_list() {
    StudentList* list = (StudentList*)malloc(sizeof(StudentList));
    if (list == NULL) {
        fprintf(stderr, "内存分配失败: 无法创建学生链表\n");
        return NULL;
    }
    list->head = NULL;
    list->count = 0;
    printf("✅ 学生链表创建成功\n");
    return list;
}

// 释放学生链表
void free_student_list(StudentList* list) {
    if (list == NULL) return;
    
    StudentNode* current = list->head;
    StudentNode* next;
    
    while (current != NULL) {
        next = current->next;
        free(current);
        current = next;
    }
    
    free(list);
    printf("✅ 学生链表内存已释放\n");
}

// 验证学号格式
int validate_student_id(const char* id) {
    if (id == NULL || strlen(id) == 0) {
        printf("❌ 学号不能为空\n");
        return 0;
    }
    
    // 检查学号长度（通常为8-20位）
    size_t len = strlen(id);
    if (len < 8 || len > 20) {
        printf("❌ 学号长度应在8-20位之间\n");
        return 0;
    }
    
    // 检查是否只包含数字
    for (size_t i = 0; i < len; i++) {
        if (!isdigit(id[i])) {
            printf("❌ 学号应只包含数字\n");
            return 0;
        }
    }
    
    return 1;
}

// 验证学生姓名
int validate_student_name(const char* name) {
    if (name == NULL || strlen(name) == 0) {
        printf("❌ 姓名不能为空\n");
        return 0;
    }
    
    size_t len = strlen(name);
    if (len >= MAX_NAME_LEN) {
        printf("❌ 姓名过长，最大允许%d个字符\n", MAX_NAME_LEN - 1);
        return 0;
    }
    
    return 1;
}

// 查找学生
Student* find_student(StudentList* list, const char* id) {
    if (list == NULL || id == NULL) {
        return NULL;
    }
    
    StudentNode* current = list->head;
    while (current != NULL) {
        if (strcmp(current->student.id, id) == 0) {
            return &(current->student);
        }
        current = current->next;
    }
    
    return NULL;
}

// 添加学生
int add_student(StudentList* list, const char* id, const char* name) {
    if (list == NULL) {
        printf("❌ 学生链表未初始化\n");
        return 0;
    }
    
    // 验证输入
    if (!validate_student_id(id) || !validate_student_name(name)) {
        return 0;
    }
    
    // 检查学号是否已存在
    if (find_student(list, id) != NULL) {
        printf("❌ 学号 %s 已存在\n", id);
        return 0;
    }
    
    // 创建新学生节点
    StudentNode* new_node = (StudentNode*)malloc(sizeof(StudentNode));
    if (new_node == NULL) {
        printf("❌ 内存分配失败: 无法创建新学生\n");
        return 0;
    }
    
    // 初始化学生信息
    strcpy(new_node->student.id, id);
    strcpy(new_node->student.name, name);
    new_node->student.course_count = 0;
    new_node->student.total_credits = 0.0;
    new_node->next = NULL;
    
    // 添加到链表
    if (list->head == NULL) {
        list->head = new_node;
    } else {
        StudentNode* current = list->head;
        while (current->next != NULL) {
            current = current->next;
        }
        current->next = new_node;
    }
    
    list->count++;
    printf("✅ 学生添加成功: %s - %s\n", id, name);
    log_operation("ADD_STUDENT", id);
    return 1;
}

// 删除学生
int delete_student(StudentList* list, const char* id) {
    if (list == NULL || list->head == NULL) {
        printf("❌ 学生链表为空\n");
        return 0;
    }
    
    if (!validate_student_id(id)) {
        return 0;
    }
    
    StudentNode* current = list->head;
    StudentNode* prev = NULL;
    
    // 查找要删除的学生
    while (current != NULL) {
        if (strcmp(current->student.id, id) == 0) {
            break;
        }
        prev = current;
        current = current->next;
    }
    
    if (current == NULL) {
        printf("❌ 未找到学号为 %s 的学生\n", id);
        return 0;
    }
    
    // 从链表中移除
    if (prev == NULL) {
        list->head = current->next;
    } else {
        prev->next = current->next;
    }
    
    printf("✅ 学生删除成功: %s - %s\n", current->student.id, current->student.name);
    log_operation("DELETE_STUDENT", id);
    free(current);
    list->count--;
    
    return 1;
}

// 更新学生信息
int update_student(StudentList* list, const char* id, const char* new_name) {
    if (list == NULL) {
        printf("❌ 学生链表未初始化\n");
        return 0;
    }
    
    if (!validate_student_id(id) || !validate_student_name(new_name)) {
        return 0;
    }
    
    Student* student = find_student(list, id);
    if (student == NULL) {
        printf("❌ 未找到学号为 %s 的学生\n", id);
        return 0;
    }
    
    char old_name[MAX_NAME_LEN];
    strcpy(old_name, student->name);
    strcpy(student->name, new_name);
    
    printf("✅ 学生信息更新成功: %s (%s -> %s)\n", id, old_name, new_name);
    log_operation("UPDATE_STUDENT", id);
    return 1;
}

// 检查课程是否已选
int is_course_already_selected(Student* student, const char* course_id) {
    for (int i = 0; i < student->course_count; i++) {
        if (strcmp(student->selected_courses[i], course_id) == 0) {
            return 1;
        }
    }
    return 0;
}

// 更新学生学分
void update_student_credits(Student* student, float credit_change) {
    student->total_credits += credit_change;
    if (student->total_credits < 0) {
        student->total_credits = 0;
    }
}

// 为学生添加课程
int add_course_to_student(StudentList* list, const char* student_id, 
                         const char* course_id, float credits) {
    if (list == NULL) {
        printf("❌ 学生链表未初始化\n");
        return 0;
    }
    
    Student* student = find_student(list, student_id);
    if (student == NULL) {
        printf("❌ 未找到学号为 %s 的学生\n", student_id);
        return 0;
    }
    
    // 检查课程是否已选
    if (is_course_already_selected(student, course_id)) {
        printf("❌ 学生 %s 已选择课程 %s\n", student_id, course_id);
        return 0;
    }
    
    // 检查选课数量限制
    if (student->course_count >= MAX_COURSES) {
        printf("❌ 学生 %s 选课数量已达上限(%d门)\n", student_id, MAX_COURSES);
        return 0;
    }
    
    // 添加课程
    strcpy(student->selected_courses[student->course_count], course_id);
    student->course_count++;
    update_student_credits(student, credits);
    
    printf("✅ 学生 %s 成功选择课程 %s (%.1f学分)\n", 
           student_id, course_id, credits);
    log_operation("ADD_COURSE_TO_STUDENT", student_id);
    return 1;
}

// 为学生退课
int remove_course_from_student(StudentList* list, const char* student_id, 
                              const char* course_id) {
    if (list == NULL) {
        printf("❌ 学生链表未初始化\n");
        return 0;
    }
    
    Student* student = find_student(list, student_id);
    if (student == NULL) {
        printf("❌ 未找到学号为 %s 的学生\n", student_id);
        return 0;
    }
    
    // 查找课程位置
    int course_index = -1;
    for (int i = 0; i < student->course_count; i++) {
        if (strcmp(student->selected_courses[i], course_id) == 0) {
            course_index = i;
            break;
        }
    }
    
    if (course_index == -1) {
        printf("❌ 学生 %s 未选择课程 %s\n", student_id, course_id);
        return 0;
    }
    
    // 移除课程（需要获取课程学分，这里假设通过参数传入或从其他地方获取）
    // 这里我们暂时不减学分，因为学分信息需要从课程模块获取
    // 在实际使用中，应该从课程模块获取该课程的学分
    
    // 将后面的课程前移
    for (int i = course_index; i < student->course_count - 1; i++) {
        strcpy(student->selected_courses[i], student->selected_courses[i + 1]);
    }
    
    student->course_count--;
    printf("✅ 学生 %s 成功退选课程 %s\n", student_id, course_id);
    log_operation("REMOVE_COURSE_FROM_STUDENT", student_id);
    return 1;
}

// 显示学生详细信息
void display_student_details(Student* student) {
    if (student == NULL) {
        printf("❌ 学生信息为空\n");
        return;
    }
    
    printf("\n════════════════════════════════════════\n");
    printf("学号: %s\n", student->id);
    printf("姓名: %s\n", student->name);
    printf("已选课程数量: %d\n", student->course_count);
    printf("总学分: %.1f\n", student->total_credits);
    
    if (student->course_count > 0) {
        printf("已选课程列表:\n");
        for (int i = 0; i < student->course_count; i++) {
            printf("  %d. %s\n", i + 1, student->selected_courses[i]);
        }
    } else {
        printf("尚未选择任何课程\n");
    }
    printf("════════════════════════════════════════\n");
}

// 显示所有学生
void display_all_students(StudentList* list) {
    if (list == NULL || list->head == NULL) {
        printf("❌ 没有学生信息\n");
        return;
    }
    
    printf("\n════════════════════════════════════════\n");
    printf("           所有学生信息 (%d人)\n", list->count);
    printf("════════════════════════════════════════\n");
    
    StudentNode* current = list->head;
    int count = 1;
    
    while (current != NULL) {
        printf("%d. %s - %s (课程:%d, 学分:%.1f)\n", 
               count++, 
               current->student.id, 
               current->student.name,
               current->student.course_count,
               current->student.total_credits);
        current = current->next;
    }
    printf("════════════════════════════════════════\n");
}

// 学生管理菜单
void student_management_menu(StudentList* list) {
    if (list == NULL) {
        printf("❌ 学生链表未初始化\n");
        return;
    }
    
    int choice;
    char id[20], name[MAX_NAME_LEN], course_id[20];
    
    do {
        printf("\n════════════════════════════════════════\n");
        printf("           学生信息管理\n");
        printf("════════════════════════════════════════\n");
        printf("1. 添加学生\n");
        printf("2. 删除学生\n");
        printf("3. 修改学生信息\n");
        printf("4. 查找学生\n");
        printf("5. 显示所有学生\n");
        printf("6. 学生选课\n");
        printf("7. 学生退课\n");
        printf("0. 返回主菜单\n");
        printf("════════════════════════════════════════\n");
        printf("请选择操作: ");
        
        scanf("%d", &choice);
        
        switch (choice) {
            case 1:
                printf("请输入学号: ");
                scanf("%s", id);
                printf("请输入姓名: ");
                scanf("%s", name);
                add_student(list, id, name);
                break;
                
            case 2:
                printf("请输入要删除的学生学号: ");
                scanf("%s", id);
                delete_student(list, id);
                break;
                
            case 3:
                printf("请输入要修改的学生学号: ");
                scanf("%s", id);
                printf("请输入新的姓名: ");
                scanf("%s", name);
                update_student(list, id, name);
                break;
                
            case 4:
                printf("请输入要查找的学生学号: ");
                scanf("%s", id);
                Student* student = find_student(list, id);
                if (student != NULL) {
                    display_student_details(student);
                } else {
                    printf("❌ 未找到学号为 %s 的学生\n", id);
                }
                break;
                
            case 5:
                display_all_students(list);
                break;
                
            case 6:
                printf("请输入学生学号: ");
                scanf("%s", id);
                printf("请输入课程编号: ");
                scanf("%s", course_id);
                // 学分需要从课程模块获取，这里暂时设为0
                add_course_to_student(list, id, course_id, 0);
                break;
                
            case 7:
                printf("请输入学生学号: ");
                scanf("%s", id);
                printf("请输入课程编号: ");
                scanf("%s", course_id);
                remove_course_from_student(list, id, course_id);
                break;
                
            case 0:
                printf("返回主菜单...\n");
                break;
                
            default:
                printf("❌ 无效的选择，请重新输入\n");
        }
        
        // 清空输入缓冲区
        while (getchar() != '\n');
        
    } while (choice != 0);
}
